package jjn.carl.backtrack;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author Jjn
 * @since 2023/7/29 10:49
 */
public class LeetCode93 {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        if (s.length() > 12 || s.length() < 4) {
            return result;
        }
        backtrack(s, result, 0, 4, new ArrayList<>());
        return result;
    }
    
    private void backtrack(String s, List<String> result, int startIndex, int pointNum, List<String> parts) {
        // 终止条件
        if (startIndex == s.length()) {
            if (pointNum == 0) {
                result.add(String.join(".", parts));
                return;
            }
        }
        for (int i = startIndex; i < startIndex + 3; i++) {
            // 避免越界
            if (i >= s.length()) {
                break;
            }
            // 剪枝操作
            if (s.length() - i > pointNum * 3) {
                continue;
            }
            if (isValidPart(s, startIndex, i)) {
                parts.add(s.substring(startIndex, i + 1));
                backtrack(s, result, i + 1, pointNum - 1, parts);
                parts.remove(parts.size() - 1);
            }
        }
    }
    
    private boolean isValidPart(String s, int start, int end) {
        if (s == null || s.isEmpty()) {
            return false;
        }
        int subLength = end - start + 1;
        if (subLength > 3) {
            return false;
        }
        if (subLength > 1) {
            if (s.charAt(start) == '0') {
                return false;
            }
        }
        int sum = 0;
        for (int i = start; i <= end; i++) {
            int ithChar = s.charAt(i) - '0';
            sum = 10 * sum + ithChar;
        }
        return sum >= 0 && sum <= 255;
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        List<String> addresses = new LeetCode93().restoreIpAddresses(s);
        System.out.println(addresses.toString());
    }
}
